<template>
  <!-- 验证码登录 -->
  <div class="v-code">
    <el-form
      :model="loginFormCaptcha"
      status-icon
      :rules="rules"
      ref="loginFormCaptchaRef"
      label-width="100px"
      label-position="left"
      hide-required-asterisk
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="loginFormCaptcha.phone"></el-input>
      </el-form-item>
      <el-form-item label="验证码">
        <el-input placeholder="请输入内容" v-model="loginFormCaptcha.captcha">
          <el-button slot="append" @click="getCaptcha" :disabled="isdisabled">发送验证码
            <span v-if="isdisabled">({{restOfTheTime}}s)</span>
          </el-button>
        </el-input>
      </el-form-item>
      <div class="btn">
        <el-button type="primary" @click="doLogin">提交</el-button>
        <el-button @click="resetForm('loginFormCaptchaRef')">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { sendCaptcha, login } from '../../api/login.js'
export default {
  data () {
    // 验证规则定义
    // 手机号验证
    const checkPhone = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }

    return {
      loginFormCaptcha: {
        // 手机,密码是必选参数
        phone: '',
        password: '',
        // 验证码
        captcha: ''
      },
      // 验证规则
      rules: {
        phone: [
          // { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 按钮禁用
      isdisabled: false,
      // 倒计时60秒
      restOfTheTime: 60
    }
  },
  props: [],
  methods: {
    async getCaptcha () {
      this.delay60()
      const res = await sendCaptcha(this.loginFormCaptcha.phone)
      if (res.status !== 200) return this.$message.error('获取验证码失败')
    },
    delay60 () {
      // 发送完等六十秒才能再发
      this.isdisabled = true
      setTimeout(() => {
        this.isdisabled = false
      }, 60000)
      // 倒计时
      this.countdown()
    },
    // 倒计时
    countdown () {
      const id = setInterval(() => {
        if (this.restOfTheTime === 0) {
          clearInterval(id)
          this.restOfTheTime = 60
        }
        this.restOfTheTime--
      }, 1000)
    },
    // 执行登录
    // 感觉这个登录可以和手机密码抽出来在vuex里一起
    doLogin () {
      this.$refs.loginFormCaptchaRef.validate(async (valid) => {
        if (!valid) this.$message.error('请输入正确手机号')
        const res = await login(this.loginFormCaptcha)
        if (res.data.code !== 200) return this.$message.error('登录失败')
        this.$message.success('登录成功')
        this.$router.push('/personalRecom')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.btn {
  text-align: left;
}
</style>
